package com.google.code.opencode.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.unto.twitter.Api;

import com.google.code.opencode.dao.FeedDao;
import com.google.code.opencode.model.Feed;
import com.google.code.opencode.service.Reader;
import com.google.code.opencode.service.TwitterUpdater;

public class TwitterUpdaterImpl implements TwitterUpdater {

	private static Logger logger = LoggerFactory.getLogger(TwitterUpdaterImpl.class);
	private List<Feed> opencodeList;
	private Api api;
	private FeedDao feedDao;
	private Reader reader = new RSSReader();
	private boolean devEnvironment = true;
	private String username;
	private String password;

	public void init() {
		api = Api.builder().username(username).password(password).build();
	}

	@Override
	public boolean sendUpdate() {
		logger.debug("About to send the information to the twitter account.");

		opencodeList = feedDao.lookup();

		for (Feed opencodeFeed : opencodeList) {
			String status = null;
			try {
				status = reader.read(opencodeFeed);
			}
			catch (Exception e) {
				logger.warn("There was an excepion while processing feed: " + opencodeFeed.getName(), e);
			}

			// only update if:
			// a) the is a new status
			// b) the status is different from the last one
			if (status != null && !status.isEmpty()
					&& !status.equals(opencodeFeed.getLastPublishedStatus())) {

				if (devEnvironment) {
					logger.info("status: " + status);
				}
				else {
					logger.info("updateStatus: " + status);
					api.updateStatus(status).build().post();
				}
				opencodeFeed.setLastPublishedStatus(status);
				feedDao.update(opencodeFeed);
			}
		}

		logger.debug("Sent the information to the twitter account.");

		return true;
	}

	@Override
	public void setFeedDao(FeedDao feedDao) {
		this.feedDao = feedDao;
	}

	@Override
	public void setDevEnvironment(boolean devEnvironment) {
		this.devEnvironment = devEnvironment;
	}

	@Override
	public void setUsername(String username) {
		this.username = username;
	}

	@Override
	public void setPassword(String password) {
		this.password = password;
	}
}
